package com.hmall.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
// @Order(-1)
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchangeexchange, GatewayFilterChain chain) {

        //获取头信息
        ServerHttpRequest request = exchangeexchange.getRequest();
        ServerHttpResponse response = exchangeexchange.getResponse();


        // 获取参数
        String userId = request.getHeaders().getFirst("authorization");

        if ("2".equals(userId)) {
            //放行
           return chain.filter(exchangeexchange);


        }

        // 不放行
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        log.error("用户身份校验失败，当前用户为：{}",userId);
        return response.setComplete();


    }

    @Override
    public int getOrder() {
        return 2;
    }
}
